#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from common.common_models import SubJobModel
from exchange import log

from exchange.commons.common import output_result_file
from exchange.commons.const import ExchangeJobInfo, SubJobPolicy, SubJobType, SubJobPriorityEnum, \
    ExchangeBackupSubJobName
from exchange.commons.exchange_function_tool import log_start_end
from exchange.restore.restore_param_parser import RestoreParamParser


# Exchange分发子任务基类
class ExchangeRestoreGenSubJob:
    def __init__(self, pid, param):
        self._pid = pid
        self._param = param

    @staticmethod
    def build_sub_job(job_priority, policy, job_name, node_id, job_info: ExchangeJobInfo):
        return SubJobModel(jobId=job_info.job_id, jobType=SubJobType.BUSINESS_SUB_JOB.value, execNodeId=node_id,
                           jobPriority=job_priority, jobName=job_name, policy=policy,
                           ignoreFailed=False).dict(by_alias=True)

    @log_start_end()
    def do_gen_sub_job_task(self, job_info: ExchangeJobInfo):
        nodes_list = RestoreParamParser.get_restore_nodes_list(self._param)
        node_id = nodes_list[0].get("id", "")
        response = []

        # 第一个子任务，创建备份任务
        job_policy = SubJobPolicy.FIXED_NODE.value
        job_name = ExchangeBackupSubJobName.SUB_EXEC
        job_priority = SubJobPriorityEnum.JOB_PRIORITY_1.value
        response.append(self.build_sub_job(job_priority, job_policy, job_name, node_id, job_info))
        log.info(f"Gen sub job result： {response}")
        output_result_file(job_info.pid, response)
        return True